package com.tws.pctask.service;

import cn.hutool.core.util.IdUtil;
import cn.hutool.extra.mail.MailUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.tws.common.enums.ResultEnum;
import com.tws.common.model.ResponseWrapper;
import com.tws.common.tool.GraphicVerification;
import com.tws.dao.entity.User;
import com.tws.dao.mapper.UserMapper;
import com.tws.pctask.mapper.RegisterMapper;
import com.tws.pctask.model.registerManageModel.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Map;

/**
 * @Description： 注册服务层
 * @Author: wbf
 * @Date: 2022/1/18 14:31
 */
@Service
public class RegisterService {

    @Autowired
    private UserMapper userMapper;

    //邮箱验证码
    private String imageCode;
    /**
     * 2.1获取邮箱验证码
     * @param param 邮箱
     * @return 验证码
     */
    public ResponseWrapper getEmailCode(GetEmailCodeParam param){
        Map<String, String> map = GraphicVerification.CreatGraphicVerification();
        imageCode = map.get("imageCode");
        String content = EmailHtmlStyle.head + map.get("imageCode")+ EmailHtmlStyle.tail;
        MailUtil.send(param.getUserEmail(), "您的帐户需要邮件辅助验证", content, true);
        return ResponseWrapper.markSuccess();
    }

    /**
     * 2.2检查用户名是否重复
     * @param param 用户名
     * @return true为重复 false为不重复
     */
    public ResponseWrapper checkName(CheckNameParam param){
        LambdaQueryWrapper<User> selectByName = new LambdaQueryWrapper<>();
        selectByName.eq(null != param.getUserName(), User::getUserName,param.getUserName());
        User user = userMapper.selectOne(selectByName);
        CheckNameResult result = new CheckNameResult(user != null);
        return ResponseWrapper.markSuccess(result);
    }

    /**
     * 2.3检查邮箱是否重复
     * @param param 邮箱
     * @return true为重复 false为不重复
     */
    public ResponseWrapper checkEmail(CheckEmailParam param){
        LambdaQueryWrapper<User> selectByEmail = new LambdaQueryWrapper<>();
        selectByEmail.eq(User::getUserEmail,param.getUserEmail());
        User user = userMapper.selectOne(selectByEmail);
        CheckEmailResult result = new CheckEmailResult(user != null);
        return ResponseWrapper.markSuccess(result);
    }

    @Autowired
    RegisterMapper registerMapper;
    /**
     * 2.4注册用户
     * @param param 注册参数
     * @return 注册结果
     */
    @Transactional(rollbackFor = Exception.class)
    public ResponseWrapper registerUser(RegisterUserParam param){
        User newUser = JSON.parseObject(JSON.toJSONString(param),User.class);
        newUser.setUserIdentity(1);//默认为用户
        newUser.setUserState(0);//默认不欠费
        newUser.setDeadline(30);//新用户默认使用30天
        /**
         * 用户名和邮箱查重
         */
        CheckNameResult nameResult = (CheckNameResult) checkName(new CheckNameParam(param.getUserName())).getData();
        if(nameResult.getIsExist()){return ResponseWrapper.markError(ResultEnum.USER_EXISTS);}
        CheckEmailResult emailResult = (CheckEmailResult)checkEmail(new CheckEmailParam(param.getUserEmail())).getData();
        if(emailResult.getIsExist()){return ResponseWrapper.markError(ResultEnum.USER_EMAIL_EXISTS);}

        /**
         * 生成ID 日期+uuid
         */
        LocalDateTime now = LocalDateTime.now();
        DateTimeFormatter df = DateTimeFormatter.ofPattern("MMdd");
        String currentTime = df.format(now);
        String userId = currentTime+IdUtil.randomUUID().split("-")[0];
        newUser.setUserId(userId);

        if(param.getEmailCode().equals(imageCode)) {
            userMapper.insert(newUser); //新增用户
            registerMapper.creatDepartmentTable(new CreatTables(newUser.getUserId())); //创建用户相关表
            return ResponseWrapper.markSuccess();
        }
        else{ return ResponseWrapper.markError(ResultEnum.CAPTCHA_CHECK_ERROR);}
    }
}
